﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Diagnostics;

namespace DIProject.ReceptionGoods
{
    public partial class MoronRows : Form
    {
        private List<DataSets.waybillsData.MoronRow> badRows = new List<DataSets.waybillsData.MoronRow>();
      //  private DataSets.waybillsData.MoronDataTable badRows1 = new DIProject.DataSets.waybillsData.MoronDataTable();
        private List<DataSets.waybillsData.MoronRow> goodRows = new List<DIProject.DataSets.waybillsData.MoronRow>();
     //   private DataSets.waybillsData.MoronDataTable goodRows1 = new DIProject.DataSets.waybillsData.MoronDataTable();
        private DataSets.waybillsData.MoronDataTable _data;
        public MoronRows(DataSets.waybillsData.MoronDataTable data,Int32 contragentId,string docNumber,DateTime docDate)
        {
            _data = data;
            DocNumber = docNumber;
            this.DocDate = docDate;
            ContragentId = contragentId;
            InitializeComponent();
        }
        private string _note;

        public string Note
        {
            get { return _note; }
            set { _note = value; }
        }

        private DateTime? _paymentDate = null;
        /// <summary>
        /// Дата оплаты документа
        /// </summary>
        public DateTime? PaymentDate
        {
            get 
            {
                if (_paymentDate == null)
                    return DateTime.Now;
                return _paymentDate; 
            }
            set { _paymentDate = value; }
        }

        private DateTime _docDate;
        /// <summary>
        /// Дата накладной поставщика
        /// </summary>
        public DateTime DocDate
        {
            get 
            {
                if (_docDate == null)
                    return DateTime.Now;
                DateTime result = new DateTime(_docDate.Year, _docDate.Month, _docDate.Day);
                return result;
            }
            set { _docDate = value; }
        }

        private string _docNumber;
        /// <summary>
        /// Номер накладной
        /// </summary>
        public string DocNumber
        {
            get 
            {
                if (_docNumber == null)
                    return string.Empty;
                return _docNumber; 
            }
            set { _docNumber = value; }
        }

        private Int32 _contragentId;
        /// <summary>
        /// идентификатор контрагента
        /// </summary>
        public Int32 ContragentId
        {
            get { return _contragentId; }
            set { _contragentId = value; }
        }

        private void MoronRows_Load(object sender, EventArgs e)
        {
            dgvMoronRows.DataSource = _data;
           //btnInsert.Enabled = false;
            cbNkldFilter.ComboBox.DataSource = this.Nklds;
        }
        public const string AllString = "Все строки";
        private List<string> Nklds
        {
            get
            {
                List<string> res = new List<string>();
                res.Add(MoronRows.AllString);
                foreach (DataRowView drv in this._data.DefaultView)
                {
                    DataSets.waybillsData.MoronRow mr = drv.Row as DataSets.waybillsData.MoronRow;
                    string tmp = mr.NUMNAK;
                    if (!string.IsNullOrEmpty(tmp))
                    {
                        if (!res.Contains(tmp))
                        {
                            res.Add(tmp);
                        }
                    }
                }
                return res;
            }
        }
       
        private void dgvMoronRows_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            object o1 = sender;
            object o2 = e;           
        }

        private void dgvMoronRows_KeyPress(object sender, KeyPressEventArgs e)
        {
            
        }

        private void dgvMoronRows_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
 
            }
        }
        private bool _isParse = false;

        /// <summary>
        /// признак, указывает, разбирался документ.
        /// </summary>
        public bool IsParse
        {
            get 
            { 
                return _isParse; 
            }
            set 
            { 
                _isParse = value;
               /* if (value)
                    btnInsert.Enabled = true;*/
            }
        }

        private void btnCompute_Click(object sender, EventArgs e)
        {
            _moronLink = null;
            ComputeRows();
        }
        private DataSets.waybillsData.MoronRow GetMoronRow(DataGridViewRow row)
        {
            return (row.DataBoundItem as DataRowView).Row as DataSets.waybillsData.MoronRow;
        }
        /// <summary>
        /// просматриваем таблицу, ищем перекодировки, выделяем не найденные красным
        /// </summary>
        private void ComputeRows()
        {
            foreach (DataGridViewRow row in dgvMoronRows.Rows)
            {
                DataRowView drv = row.DataBoundItem as DataRowView;
                if (drv == null)
                    throw new Util.DIException("Ощибка при разборе строк1");
                DataSets.waybillsData.MoronRow mr = drv.Row as DataSets.waybillsData.MoronRow;
                if (mr == null)
                    throw new Util.DIException("Ощибка при разборе строк2");
                //lock (mr.Table)
                {
                    if (!ValidateRow(mr))
                    {
                        dgvMoronRows.Rows[row.Index].DefaultCellStyle.BackColor = Color.Red;
                        //Debug.WriteLine(row.Cells[4].Value);
                        badRows.Add(mr);// Add(GetMoronRow(row));
                    }
                    else
                    {
                        goodRows.Add(GetMoronRow(row));
                       // goodRows1.Rows.Add(mr.ItemArray);
                    }
                }
 
            }
            this.IsParse = true;
        }
        private DataSets.Util.LinkGoodsDataTable _moronLink;
        private Int32 conId = Int32.MinValue;
        public DataSets.Util.LinkGoodsDataTable MoronLink
        {
            get
            {
                if (conId != this.ContragentId)
                {
                    _moronLink = null;
                    conId = this.ContragentId;
                }
                if (_moronLink == null)
                {
                    DataSets.UtilTableAdapters.LinkGoodsTableAdapter adapter = new DIProject.DataSets.UtilTableAdapters.LinkGoodsTableAdapter();
                    _moronLink = adapter.GetData(this.ContragentId);
                }
                return _moronLink;
            }
            
        }
        /// <summary>
        /// поиск перекодировки по строке
        /// </summary>
        /// <param name="mr"></param>
        /// <returns></returns>
        private bool ValidateRow(DataSets.waybillsData.MoronRow mr)
        {
            if (mr == null)
                throw new ArgumentNullException("mr");
            MoronLink.DefaultView.RowFilter = "GoodsCode = " + Convert.ToInt32(mr.KODNLKLEK).ToString();
            if (MoronLink.DefaultView.Count < 1)
                return false;
            foreach (DataRowView drv in MoronLink.DefaultView)
            {
                DataSets.Util.LinkGoodsRow lr = drv.Row as DataSets.Util.LinkGoodsRow;
                bool flag = //(string.Compare(lr.CountryName,mr.NAMSTRANA,true)==0) && (string.Compare(lr.ManufacturerName,mr.NAMZAVOD,true)==0) &&
                    (string.Compare(lr.GoodsName.Replace("№", "N").Replace("'", "").Replace("\"", ""), mr.NAMLEK.Replace("№", "N").Replace("'", "").Replace("\"", ""), true) == 0);
                if (flag)
                {
                    mr.SupplierGoodsId = lr.Id;
                    mr.GoodsId = lr.InnerGodsId;
                    return true;
                }
            }
            return false;
            
        }

        private void dgvMoronRows_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex>-1)
            {
                dgvMoronRows.Rows[e.RowIndex].Selected = true;
            }
        }

       

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (dgvMoronRows.SelectedRows.Count != 1)
            {
                MessageBox.Show("Необходимо выбрать товар!", "Выбирите товар!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                dgvMoronRows.Focus();
                return;
            }
            DataGridViewRow dgrv = dgvMoronRows.SelectedRows[0];
            DataRowView drv = dgrv.DataBoundItem as DataRowView;
            DataSets.waybillsData.MoronRow mr = drv.Row as DataSets.waybillsData.MoronRow;
            ReceptionGoods.LinksMoron ml = new LinksMoron(mr, this.ContragentId);
           // ml.MdiParent = this.MdiParent;
            DialogResult dr = ml.ShowDialog(this);
            if (dr == DialogResult.OK)
            {
                dgvMoronRows.SelectedRows[0].DefaultCellStyle.BackColor = Color.White;
               // badRows1.Rows.Remove(new DataSets.waybillsData.MoronRow(mr);
                goodRows.Add(mr);               
            }

        }
        #region удаление
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (dgvMoronRows.SelectedRows.Count != 1)
            {
                MessageBox.Show("Необходимо выбрать строку!", "Выбирите строку!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                dgvMoronRows.Focus();
                return;
            }
            if (MessageBox.Show("Удалить строку?","Удаление",MessageBoxButtons.OKCancel,MessageBoxIcon.Question) != DialogResult.OK)
                return;
            DataGridViewRow dr = dgvMoronRows.SelectedRows[0];
            DataRowView drv = dr.DataBoundItem as DataRowView;
            DataSets.waybillsData.MoronRow mr = drv.Row as DataSets.waybillsData.MoronRow;
            DataSets.waybillsData.MoronDataTable dt = mr.Table as DataSets.waybillsData.MoronDataTable;
            dt.Rows.Remove(mr);
            dt.AcceptChanges();
            RecolorBadRows();
        }
        /// <summary>
        /// перераскрашиваем строки по которым нет перекодировки
        /// </summary>
        private void RecolorBadRows()
        {
            foreach (DataGridViewRow row in dgvMoronRows.Rows)
            {
                if (badRows.Find(delegate(DataSets.waybillsData.MoronRow r) { return r == GetMoronRow(row); }) != null)
                {
                    row.DefaultCellStyle.BackColor = Color.Red;
                }
            }
        }
        #endregion
        /// <summary>
        /// считаем сумму НДС по строке
        /// </summary>
        /// <param name="mr"></param>
        /// <returns></returns>
        private double GetNDSValue(DataSets.waybillsData.MoronRow mr)
        {
            if (mr == null)
                throw new ArgumentException("mr");
            double priceManuf = mr.CENAPRBNDS;
            double priceDistr = mr.CENAPROD;
            double count = mr.COUNT;
            double resulr = (priceDistr - priceManuf) * count;
            return resulr;
        }
        List<DataSets.waybillsData.MoronRow> badLines = new List<DIProject.DataSets.waybillsData.MoronRow>();
        DataSets.waybillsData.MoronDataTable badLines1 = new DIProject.DataSets.waybillsData.MoronDataTable();
        DateTime MaxSmallDateTime = new DateTime(2070, 1, 1);
        DateTime MinSmallDateTime = new DateTime(1900, 1, 1);
        private string NewDocNumber
        {
            get
            {
                if (cbNkldFilter.Text == MoronRows.AllString)
                    return this.DocNumber;
                return cbNkldFilter.Text;
            }
        }
        private void btnInsert_Click(object sender, EventArgs e)
        {           
            
            if (goodRows.Count < 1)
                throw new Util.DIException("Ошибка импорта накладной");
            
                badLines.Clear();
                PaymentDateForm pdf = new PaymentDateForm(this);
                pdf.ShowDialog(this);
                DataSets.waybillsData.SupplierInvoiceDocInsertDataTable docHeader = Data.Nkld.SupplierInvoiceDocInsert(Util.Common.CurrentSmallDate, null, this.ContragentId,
                    this.DocDate, this.NewDocNumber, this.PaymentDate, this.Note, DateTime.Now, Environment.UserDomainName);
                DataSets.waybillsData.SupplierInvoiceDocInsertRow rh = docHeader.Rows[0] as DataSets.waybillsData.SupplierInvoiceDocInsertRow;
               foreach (DataSets.waybillsData.MoronRow mr in this.goodRows)
                {
                    try
                    {
                        PrintRow(mr);
                        Int32? KODORG = null;
                        if (!mr.IsKODORGNull())
                            KODORG = Convert.ToInt32(mr.KODORG);
                        DateTime? SROK = null;
                        if (!mr.IsSROKNull())
                        {
                            System.Diagnostics.Debug.Write(mr.SROK.ToString());
                            if ((mr.SROK < MaxSmallDateTime) && (mr.SROK > MinSmallDateTime))
                                SROK = mr.SROK;
                            else
                                SROK = MaxSmallDateTime;
                            System.Diagnostics.Debug.WriteLine(SROK.Value.ToString());
                        }
                        decimal? SupplierSumNOTAX = null;
                        SupplierSumNOTAX = Convert.ToDecimal(Convert.ToInt32(mr.COUNT) * mr.CENAPROD);
                        decimal NDSValue = Convert.ToDecimal(GetNDSValue(mr));
                        byte NDS = Convert.ToByte(mr.PRCNDS);
                        Int32 COUNT = 0;
                        if (!mr.IsCOUNTNull())
                            COUNT = Convert.ToInt32(mr.COUNT);
                        decimal? CENAPROD = null;
                        if (!mr.IsCENAPRODNull())
                            CENAPROD = Convert.ToDecimal(mr.CENAPROD);
                        decimal? CENARAS = null;
                        if (!mr.IsCENARASNull())
                            CENARAS = Convert.ToDecimal(mr.CENARAS);
                        decimal? CENAREE = null;
                        if (!mr.IsCENAREENull())
                            CENAREE = Convert.ToDecimal(mr.CENAREE);
                        double? NACIMP = null;
                        if (!mr.IsNACIMPNull())
                            NACIMP = mr.NACIMP;
                        double? NACOPT = null;
                        if (!mr.IsNACOPTNull())
                            NACOPT = mr.NACOPT;
                        DIProject.Data.Nkld.SupplierInvoiceLinesInsert(rh.Id, mr.GoodsId, mr.EAN13, 
                            COUNT,
                            null, mr.SupplierGoodsId, CENARAS, 
                            CENAPROD,SupplierSumNOTAX,
                            NACIMP, NACOPT, mr.SERIJ, GetSrokGod(mr),
                            null, NDS, NDSValue, 
                            CENAREE, GetDateRee(mr), null, mr.NUMBER,
                            SROK,KODORG , null, null, string.Empty, DateTime.Now, FirstForm.Login);
                    }
                    catch (Exception ee)
                    {
                        System.Diagnostics.Debug.Write(ee.ToString());
                        badLines.Add(mr);
                       // badLines1.Rows.Add(mr.ItemArray);
                    }
                }
                if (badLines.Count > 0)
                {
                    MessageBox.Show("Не удалось вставить " + badLines.Count.ToString() + " строк из " + goodRows.Count.ToString());
                }
                this.Close();
        }
        private DateTime? GetDateRee(DataSets.waybillsData.MoronRow mr)
        {
            if (mr.IsDATAREENull())
                return null;
            if ((mr.DATAREE > MaxSmallDateTime) || (mr.DATAREE < MinSmallDateTime))
                return null;
            return Util.Common.ConvertToSmall(mr.DATAREE);
        }
        private DateTime? GetSrokGod(DataSets.waybillsData.MoronRow mr)
        {
            if (mr.IsSROKGODNull())
                return null;
            if ((mr.SROKGOD > MaxSmallDateTime) || (mr.SROKGOD < MinSmallDateTime))
                return null;
            return Util.Common.ConvertToSmall( mr.SROKGOD);
        }
        private void PrintRow(DataRow dr)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            for (Int32 i = 0; i < dr.ItemArray.Length; i++)
            {                
                sb.Append(dr.ItemArray[i].ToString() + "\t");
            }
            System.Diagnostics.Debug.Write(sb.ToString());
        }

        private void cbNkldFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            string tmp = cbNkldFilter.ComboBox.SelectedItem as string;
            if (tmp == MoronRows.AllString)
                this._data.DefaultView.RowFilter = string.Empty;
            else
                this._data.DefaultView.RowFilter = "NUMNAK ='" + tmp + "'"; 
        }
    }
}